package com.business_clean.app.uitl;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.business_clean.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class PhotoBitmapUtils {

    /**
     * 存放拍摄图片的文件夹
     */
    private static final String FILES_NAME = "/MyPhoto";
    /**
     * 获取的时间格式
     */
    public static final String TIME_STYLE = "yyyyMMddHHmmss";
    /**
     * 图片种类
     */
    public static final String IMAGE_TYPE = ".png";

    // 防止实例化
    private PhotoBitmapUtils() {
    }

    /**
     * 获取手机可存储路径
     *
     * @param context 上下文
     * @return 手机可存储路径
     */
    private static String getPhoneRootPath(Context context) {
        // 是否有SD卡
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || !Environment.isExternalStorageRemovable()) {
            // 获取SD卡根目录
            return context.getExternalCacheDir().getPath();
        } else {
            // 获取apk包下的缓存路径T
            return context.getCacheDir().getPath();
        }
    }

    /**
     * 使用当前系统时间作为上传图片的名称
     *
     * @return 存储的根路径+图片名称
     */
    public static String getPhotoFileName(Context context) {
        File file = new File(getPhoneRootPath(context) + FILES_NAME);
        // 判断文件是否已经存在，不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        // 设置图片文件名称
        SimpleDateFormat format = new SimpleDateFormat(TIME_STYLE, Locale.getDefault());
        Date date = new Date(System.currentTimeMillis());
        String time = format.format(date);
        String photoName = "/" + time + IMAGE_TYPE;
        return file + photoName;
    }

    /**
     * 保存Bitmap图片在SD卡中
     * 如果没有SD卡则存在手机中
     *
     * @param mbitmap 需要保存的Bitmap图片
     * @return 保存成功时返回图片的路径，失败时返回null
     */
    public static String savePhotoToSD(Bitmap mbitmap, Context context) {
        FileOutputStream outStream = null;
        String fileName = getPhotoFileName(context);
        try {
            outStream = new FileOutputStream(fileName);
            // 把数据写入文件，100表示不压缩
            mbitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (outStream != null) {
                    // 记得要关闭流！
                    outStream.close();
                }
                if (mbitmap != null) {
                    mbitmap.recycle();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 把原图按1/10的比例压缩
     *
     * @param path 原图的路径
     * @return 压缩后的图片
     */
    public static Bitmap getCompressPhoto(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 10;  // 图片的大小设置为原来的十分之一
        Bitmap bmp = BitmapFactory.decodeFile(path, options);
        options = null;
        return bmp;
    }

    /**
     * 处理旋转后的图片
     *
     * @param originpath 原图路径
     * @param context    上下文
     * @return 返回修复完毕后的图片路径
     */
    public static String amendRotatePhoto(String originpath, Context context) {

        // 取得图片旋转角度
        int angle = readPictureDegree(originpath);
        if (angle > 0) {
            LogUtils.e("图片被旋转了" + angle);
            // 把原图压缩后得到Bitmap对象
            Bitmap bmp = getCompressPhoto(originpath);

            // 修复图片被旋转的角度
            Bitmap bitmap = rotaingImageView(angle, bmp);

            // 保存修复后的图片并返回保存后的图片路径
            return savePhotoToSD(bitmap, context);
        } else {
            return originpath;
        }

    }

    /**
     * 读取照片旋转角度
     *
     * @param path 照片路径
     * @return 角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                default:
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转图片
     *
     * @param angle  被旋转角度
     * @param bitmap 图片对象
     * @return 旋转后的图片
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        return returnBm;
    }

    /**
     * 翻转相机
     *
     * @param bmp
     * @return
     */
    public static Bitmap convertBmp(Bitmap bmp) {
        int w = bmp.getWidth();
        int h = bmp.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(-1, 1); // 镜像水平翻转
        Bitmap convertBmp = Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true);

        return convertBmp;
    }

    /**
     * 旋转并缩放对应的bitmap
     *
     * @param b
     * @param degrees
     * @param maxSideLen
     * @param recycle
     * @return
     */
    public static Bitmap rotateAndScale(Bitmap b, int degrees, float maxSideLen, boolean recycle) {
        if (null == b || degrees == 0 && b.getWidth() <= maxSideLen + 10 && b.getHeight() <= maxSideLen + 10) {
            return b;
        }

        Matrix m = new Matrix();
        if (degrees != 0) {
            m.setRotate(degrees);
        }

        try {
            Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
            if (null != b2 && b != b2) {
                if (recycle) {
                    b.recycle();
                }
                b = b2;
            }
        } catch (OutOfMemoryError e) {
        }

        return b;
    }


    public static Bitmap drawWaterToBitMap(Context context, Bitmap list, Bitmap bitmap, int degrees, boolean isDrawWaterMark) {
        if (list == null) {
            return bitmap;
        }

        Bitmap.Config bitmapConfig = bitmap.getConfig();
        if (bitmapConfig == null) {
            bitmapConfig = Bitmap.Config.ARGB_8888;
        }

        bitmap = bitmap.copy(bitmapConfig, true);

        Canvas canvas = new Canvas(bitmap);

        if (isDrawWaterMark) {
            Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon_base_placeholder);
            bmp = PhotoBitmapUtils.rotateAndScale(bmp, -degrees, 0, false);
            canvas.drawBitmap(bmp, bitmap.getWidth() / 2 - bmp.getWidth() / 2, bitmap.getHeight() / 2 - bmp.getHeight() / 2, null);
        }

        if (degrees == 0 || degrees == 180) {
            canvas.drawBitmap(list, SizeUtils.dp2px(15), bitmap.getHeight() - list.getHeight() - SizeUtils.dp2px(15), null);
        } else if (degrees == 90) {
            list = PhotoBitmapUtils.rotateAndScale(list, -90, 0, false);
            canvas.drawBitmap(list, bitmap.getWidth() - list.getWidth() - SizeUtils.dp2px(15), SizeUtils.dp2px(15), null);
        } else if (degrees == 270) {
            list = PhotoBitmapUtils.rotateAndScale(list, -270, 0, false);
            canvas.drawBitmap(list, SizeUtils.dp2px(15), SizeUtils.dp2px(15), null);
        }

        return bitmap;
    }

    /**
     * @param context
     * @param waterMarkBitmap 水印
     * @param originalBitmap  原图
     * @param securityView    防伪码
     * @return
     */
    public static Bitmap drawWaterToBitMap2(Context context, Bitmap waterMarkBitmap, Bitmap originalBitmap, Bitmap securityView) {
        if (waterMarkBitmap == null || originalBitmap == null) {
            return originalBitmap;
        }

        Bitmap.Config bitmapConfig = originalBitmap.getConfig();
        if (bitmapConfig == null) {
            bitmapConfig = Bitmap.Config.ARGB_8888;
        }
        originalBitmap = originalBitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(originalBitmap);
        int width = originalBitmap.getWidth();
        int height = originalBitmap.getHeight();

        //水印
        if (waterMarkBitmap != null) {
            int listWidth = waterMarkBitmap.getWidth();
            int listHeight = waterMarkBitmap.getHeight();
            if (width < listWidth || height < listHeight) {
                waterMarkBitmap = scaleByMaxBitmap(waterMarkBitmap, (int) (width * 1.0f), true);
            }
            canvas.drawBitmap(waterMarkBitmap, 0, originalBitmap.getHeight() - waterMarkBitmap.getHeight() - SizeUtils.dp2px(0), null);
        }

        //防伪码
        if (securityView != null) {
            int logoWidth = securityView.getWidth();
            int logoHeight = securityView.getHeight();
            int logoX = originalBitmap.getWidth() - logoWidth - SizeUtils.dp2px(6);
            int logoY = originalBitmap.getHeight() - logoHeight - SizeUtils.dp2px(4);
            canvas.drawBitmap(securityView, logoX, logoY, null);
        }

        return originalBitmap;
    }

    /**
     * 水印缩放
     *
     * @param bitmap
     * @param maxLength
     * @param recycle
     * @return
     */
    public static Bitmap scaleByMaxBitmap(Bitmap bitmap, int maxLength, boolean recycle) {
        int bitmapW = bitmap.getWidth();
        int bitmapH = bitmap.getHeight();
        float percentage = Math.min(bitmapW, bitmapH) / (float) Math.max(bitmapW, bitmapH);
        int minLength = (int) (maxLength * percentage);
        int scaledWidth = bitmapW > bitmapH ? maxLength : minLength;
        int scaledHeight = bitmapH > bitmapW ? maxLength : minLength;
        try {
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
            if (scaledBitmap != null && scaledBitmap != bitmap) {
                if (recycle && !bitmap.isRecycled()) {
                    bitmap.recycle();
                }
                return scaledBitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static void recyclerBitmap(Bitmap bitmap) {
        if (bitmap == null) return;
        if (bitmap.isRecycled()) return;
        bitmap.recycle();
    }


    public static Bitmap rotateBitmap(Bitmap b, int degrees, boolean recycle) {
        if (null == b || degrees == 0) {
            return b;
        }
        Matrix m = new Matrix();
        m.setRotate(degrees);
        try {
            Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
            if (null != b2 && b != b2) {
                if (recycle && !b.isRecycled()) {
                    b.recycle();
                }
                b = b2;
            }
        } catch (OutOfMemoryError e) {
            LogUtils.e(e);
        }

        return b;
    }


    public static Bitmap convertBmp(Bitmap bmp, boolean recycle) {
        int w = bmp.getWidth();
        int h = bmp.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(-1, 1); // 镜像水平翻转
        try {
            Bitmap bitmap = Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true);
            if (null != bitmap && bitmap != bmp) {
                if (recycle && !bmp.isRecycled()) {
                    bmp.recycle();
                }
                bmp = bitmap;
            }
        } catch (Exception e) {
            LogUtils.e(e);
        }
        return bmp;
    }


    /**
     * 生成缩略图
     * 缩略图是将原图等比压缩，压缩后宽、高中较小的一个等于198像素
     */
    public static Bitmap getBitmapThumb(String path, int num) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int reqWidth, reqHeight, width = options.outWidth, height = options.outHeight;
        if (width > height) {
            reqWidth = num;
            reqHeight = (reqWidth * height) / width;
        } else {
            reqHeight = num;
            reqWidth = (width * reqHeight) / height;
        }
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        try {
            options.inSampleSize = inSampleSize;
            options.inJustDecodeBounds = false;
            Matrix mat = new Matrix();
            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            ExifInterface ei = new ExifInterface(path);
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    mat.postRotate(90);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    mat.postRotate(180);
                    break;
            }
//            Log.e("test","bitmap.getWidth():"+bitmap.getWidth()+",,bitmap.getHeight():"+bitmap.getHeight());
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);
        } catch (IOException e) {
            return null;
        }
    }


    /**
     * 获取视频的第一帧缩略图
     * 先通过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图。
     * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的值，这样会节省内存。
     *
     * @param videoPath 视频的路径
     * @param width     指定输出视频缩略图的宽度
     * @param height    指定输出视频缩略图的高度度
     * @param kind      参照MediaStore.Images(Video).Thumbnails类中的常量MINI_KIND和MICRO_KIND。
     *                  其中，MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
     * @return 指定大小的视频缩略图
     */
    public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
        Bitmap bitmap = null;
        // 获取视频的缩略图
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind); //调用ThumbnailUtils类的静态方法createVideoThumbnail获取视频的截图；
        if (bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);//调用ThumbnailUtils类的静态方法extractThumbnail将原图片（即上方截取的图片）转化为指定大小；
        }
        return bitmap;
    }

}
